package com.crape.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.crape.common.bean.LoginUser;

public class LoginFilter implements Filter {

    protected FilterConfig filterConfig = null;

    private String[]       suffixArray;        // 拦截URI的后缀，如：.jsp, .xml

    private String[]       excludeArray;       // URI白名单

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
                                                                                    ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        HttpSession session = request.getSession();
        Object userObj = session.getAttribute(LoginUser.SESSION_LOGINUSER);
        String uri = request.getRequestURI();
        boolean hasSuffix = false;
        boolean isAllow = false;
        if (uri.indexOf("/admin/") > 0) {

        }
        // 判断是否在URI白名单内
        for (String exc : excludeArray) {
            if (exc.equals(uri)) {
                isAllow = true;
                break;
            } else {
                continue;
            }
        }
        if (!isAllow) {
            // 判断URI后缀是否为拦截后缀
            for (String sfx : suffixArray) {
                int i = uri.indexOf(sfx);
                if (i > 0) {
                    hasSuffix = true;
                    break;
                }
            }
            if ((userObj == null) && hasSuffix) {
                response.sendRedirect(request.getContextPath() + "/auth/login.html");
                return;
            }
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        String suffix = filterConfig.getInitParameter("suffix");
        String excludes = filterConfig.getInitParameter("excludes");
        suffixArray = suffix.split(",");
        excludeArray = excludes.split(",");
        this.filterConfig = filterConfig;
    }

}
